﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;
using System.Web.Routing;
using Common.Logging;
using Quartz;
using Quartz.Impl;

namespace MVC
{
    public class CustomPNGRouteHandler : IRouteHandler
    {
        public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return null;
            //return new CustomPNGHandler(requestContext);
        }
    }

    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.Add(new Route("images/mvcproducts/myproductname/default.png",
                new CustomPNGRouteHandler()));
            routes.Add(new Route("images/mvcproducts/default.png",
                new CustomPNGRouteHandler()));
            routes.Add(new Route("default.svg",
                new CustomPNGRouteHandler()));
            
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            
        }

        protected void Application_Start()
        {

            const string culture = "en-US";
            CultureInfo ci = CultureInfo.GetCultureInfo(culture);

            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            AreaRegistration.RegisterAllAreas();

            // Use LocalDB for Entity Framework by default
            Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);



            ILog log = LogManager.GetLogger(typeof(MvcApplication));

            log.Info("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();

            log.Info("------- Initialization Complete -----------");


            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.NextGivenSecondDate(null, 15);

            log.Info("------- Scheduling Job  -------------------");

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("job1", "group1")
                .Build();

            // Trigger the job to run on the next round minute
            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .StartAt(runTime)
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())
                .Build();

            // Tell quartz to schedule the job using our trigger
            var ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // Start up the scheduler (nothing can actually run until the 
            // scheduler has been started)
            sched.Start();
            log.Info("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to 
            // run the job!
            log.Info("------- Waiting 65 seconds... -------------");

            // wait 65 seconds to show jobs
            //Thread.Sleep(TimeSpan.FromSeconds(65));

            // shut down the scheduler
            //log.Info("------- Shutting Down ---------------------");
            //sched.Shutdown(true);
            //log.Info("------- Shutdown Complete -----------------");
        }
    }

    public class HelloJob : IJob
    {

        private static ILog _log = LogManager.GetLogger(typeof(HelloJob));

        /// <summary> 
        /// Empty constructor for job initilization
        /// <para>
        /// Quartz requires a public empty constructor so that the
        /// scheduler can instantiate the class whenever it needs.
        /// </para>
        /// </summary>
        public HelloJob()
        {
        }

        /// <summary> 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {

            // Say Hello to the World and display the date/time
            _log.Info(string.Format("Hello World! - {0}", System.DateTime.Now.ToString("r")));
        }

    }
}